package com.starpl.mobile.android.monthunsae.november.handler;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.starpl.mobile.android.monthunsae.november.R;
import com.starpl.mobile.android.monthunsae.november.activity.ProfileActivity;
import com.starpl.mobile.android.monthunsae.november.domain.UserInfo;
import com.starpl.mobile.android.platform.command.StarplCommand;
import com.starpl.mobile.android.platform.common.base.BaseApplication;
import com.starpl.mobile.android.platform.common.image.ImageDownloader;
import com.starpl.mobile.android.platform.common.network.HttpHandler;
import com.starpl.mobile.android.platform.component.BaseListHandler;
import com.starpl.mobile.android.platform.domain.StarplMessage;


/**
 * 쪽지 히스토리 리스트 핸들러
 * 상대 유저와의 쪽지 히스토리를 보여줍니다.
 * 헤더뷰에서 쪽지를 보낼 수 있습니다.
 * 헤더뷰의 버튼으로 쪽지 모두삭제 및 쪽지 차단을 할 수 있습니다.
 * 리스트의 각 아이템에서 해당 아이템(쪽지)를 삭제할 수 있습니다.
 * 
 * @author croute
 *
 */
public class MessageHistoryListHandler extends BaseListHandler implements OnClickListener
{
	private static String TAG = "MessageHistoryListHandler";
	
	private ArrayList<StarplMessage> mMessageHistoryList;
	private int mPage;

	private UserInfo mUserInfo;
	private int mSendUserIdx;
	private String mSendUserNickName;
	private String mSendUserId;

	private EditText mEtInputComment;
	private ImageButton mIbMessageBlock;
	private ImageButton mIbMessageUnblock;

	/**
	 * 쪽지 히스토리 리스트 핸들러 생성자
	 * 
	 * @param activity 액티비티
	 * @param sendUserIdx 보낸쪽지 유저Idx
	 * @param sendUserNickName 보낸쪽지 유저닉네임
	 */
	public MessageHistoryListHandler(Activity activity, int sendUserIdx, String sendUserNickName, String sendUserId)
	{
		super(activity);
		this.mMessageHistoryList = new ArrayList<StarplMessage>();
		this.mUserInfo = (UserInfo) BaseApplication.getGlobalPersistent("userInfo");
		this.mSendUserId = sendUserId;
		this.mSendUserIdx = sendUserIdx;
		this.mSendUserNickName = sendUserNickName;
		this.mPage = 1;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getArrayList()
	 */
	@Override
	public ArrayList<?> getArrayList()
	{
		return mMessageHistoryList;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getRowView(int, android.view.View)
	 */
	@Override
	public View getRowView(int position, View convertView)
	{
		StarplMessage messageHistory = mMessageHistoryList.get(position);

		MessageHistoryViewHolder messageHistoryViewHolder;

		if(convertView == null)
		{
			convertView = inflate(R.layout.message_history_row);
			messageHistoryViewHolder = new MessageHistoryViewHolder();

			// sender 변수할당
			messageHistoryViewHolder.llSenderRow = (LinearLayout) convertView
					.findViewById(R.id.message_history_row_sender_ll_row);
			messageHistoryViewHolder.ivSenderProfile = (ImageView) convertView
					.findViewById(R.id.message_history_row_sender_iv_profile);
			messageHistoryViewHolder.tvSenderComment = (TextView) convertView
					.findViewById(R.id.message_history_row_sender_tv_comment);
			messageHistoryViewHolder.tvSenderDate = (TextView) convertView
					.findViewById(R.id.message_history_row_sender_tv_date);
			messageHistoryViewHolder.ibSenderDelete = (ImageButton) convertView
					.findViewById(R.id.message_history_row_sender_ib_delete);

			messageHistoryViewHolder.ivSenderProfile.setOnClickListener(this);
			
			// receiver 변수할당
			messageHistoryViewHolder.llReceiverRow = (LinearLayout) convertView
					.findViewById(R.id.message_history_row_receiver_ll_row);
			messageHistoryViewHolder.ivReceiverProfile = (ImageView) convertView
					.findViewById(R.id.message_history_row_receiver_iv_profile);
			messageHistoryViewHolder.tvReceiverComment = (TextView) convertView
					.findViewById(R.id.message_history_row_receiver_tv_comment);
			messageHistoryViewHolder.tvReceiverDate = (TextView) convertView
					.findViewById(R.id.message_history_row_receiver_tv_date);
			messageHistoryViewHolder.ibReceiverDelete = (ImageButton) convertView
					.findViewById(R.id.message_history_row_receiver_ib_delete);

			convertView.setTag(messageHistoryViewHolder);
		}
		else
		{
			messageHistoryViewHolder = (MessageHistoryViewHolder) convertView.getTag();
		}

		if(messageHistory != null)
		{
			// 로그인된 유저가 보낸 쪽지일 때, 오른쪽(하늘색배경)
			if(mUserInfo.getUserIdx() == messageHistory.getSendUserIdx())
			{
				messageHistoryViewHolder.llSenderRow.setVisibility(LinearLayout.GONE);

				messageHistoryViewHolder.llReceiverRow.setVisibility(LinearLayout.VISIBLE);
				messageHistoryViewHolder.tvReceiverComment.setText(messageHistory.getMsgContent());
				messageHistoryViewHolder.tvReceiverDate.setText(messageHistory.getSendDate());

				// 유저의 프로필 이미지를 세팅한다.
				ImageDownloader.download(messageHistory.getSendUserProfileImgPath(),
						messageHistoryViewHolder.ivReceiverProfile, true);
				
				messageHistoryViewHolder.ibReceiverDelete.setOnClickListener(this);
				messageHistoryViewHolder.ibReceiverDelete.setTag(position);
			}
			// 다른 유저가 보낸 쪽지일 때, 왼쪽(연노랑배경)
			else
			{
				messageHistoryViewHolder.llReceiverRow.setVisibility(LinearLayout.GONE);

				messageHistoryViewHolder.llSenderRow.setVisibility(LinearLayout.VISIBLE);
				messageHistoryViewHolder.tvSenderComment.setText(messageHistory.getMsgContent());
				messageHistoryViewHolder.tvSenderDate.setText(messageHistory.getSendDate());

				// 유저의 프로필 이미지를 세팅한다.
				ImageDownloader.download(messageHistory.getSendUserProfileImgPath(),
						messageHistoryViewHolder.ivSenderProfile, true);
				
				messageHistoryViewHolder.ibSenderDelete.setOnClickListener(this);
				messageHistoryViewHolder.ibSenderDelete.setTag(position);
			}
		}

		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClick(android.view.View)
	 */
	@Override
	public void onRowClick(View v)
	{

	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onRowClear()
	 */
	@Override
	public void onRowClear()
	{
		mMessageHistoryList.clear();
		mPage = 1;
	}

	
	
	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getHeaderView()
	 */
	@Override
	public View getHeaderView()
	{
		View convertView = inflate(R.layout.message_history_header);
		
		// 헤더뷰 변수할당
		TextView tvNickname = (TextView)convertView.findViewById(R.id.message_history_header_tv_nickname);
		mEtInputComment = (EditText)convertView.findViewById(R.id.message_history_header_et_comment);
		final TextView tvLimit = (TextView)convertView.findViewById(R.id.message_history_header_tv_text_limit);
		ImageButton ibSend = (ImageButton)convertView.findViewById(R.id.message_history_header_ib_send);
		ImageButton ibDeleteAll = (ImageButton)convertView.findViewById(R.id.message_history_header_ib_delete_all);
		mIbMessageBlock = (ImageButton)convertView.findViewById(R.id.message_history_header_ib_message_block);
		mIbMessageUnblock = (ImageButton)convertView.findViewById(R.id.message_history_header_ib_message_unblock);
		
		mIbMessageBlock.setVisibility(ImageButton.INVISIBLE);
		mIbMessageUnblock.setVisibility(ImageButton.INVISIBLE);
		
		// 문자길이 제한을 하기위한 TextWatcher
		TextWatcher watcher = new TextWatcher()
		{
			@Override
			public void afterTextChanged(Editable s){}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after){}

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				String text = s.toString();
				int limitLength = 300 - text.length();
				
				tvLimit.setText(Integer.toString(limitLength));
			}
		};

		// 특정 유저에 대한 쪽지 차단 여부 판단 결과를 처리하기 위한 핸들러
		HttpHandler checkBlockHandler = new HttpHandler(mParentActivity, null)
		{
			
			/* (non-Javadoc)
			 * @see com.starpl.platform.common.network.HttpHandler#didSucceed(java.lang.Object)
			 */
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject object = ((JSONObject)result).getJSONObject("data");
					
					// 차단 유저
					if( object.isNull("rejectFlag") ? false : object.getBoolean("rejectFlag"))
					{
						mIbMessageBlock.setVisibility(ImageButton.INVISIBLE);
						mIbMessageUnblock.setVisibility(ImageButton.VISIBLE);
					}
					// 비차단 유저
					else
					{
						mIbMessageBlock.setVisibility(ImageButton.VISIBLE);
						mIbMessageUnblock.setVisibility(ImageButton.INVISIBLE);
					}
				}
				catch(JSONException e)
				{
					Log.e(TAG, e.getMessage());
				}
			}

		};
		
		StarplCommand.getRejectedUserStatus(checkBlockHandler, mSendUserIdx);
		
		// 헤더뷰 초기화 및 세팅
		mEtInputComment.addTextChangedListener(watcher);
		ibSend.setOnClickListener(this);
		ibDeleteAll.setOnClickListener(this);
		mIbMessageBlock.setOnClickListener(this);
		mIbMessageUnblock.setOnClickListener(this);
		tvNickname.setText(mSendUserNickName);
		tvLimit.setText("300");
		
		// 유저 프로필 이동을 위해 추가 등록한 클릭 리스너 : 2011.06.08
		tvNickname.setOnClickListener(this);
		
		return convertView;
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#getFooterView()
	 */
	@Override
	public View getFooterView()
	{
		return inflate(R.layout.community_footer);
	}

	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#loadContent()
	 */
	@Override
	public void loadContent()
	{
		HttpHandler getMessageHistory = new HttpHandler(mParentActivity, null)
		{
			@Override
			public void didSucceed(Object result)
			{
				try
				{
					JSONObject messageObject = (JSONObject) result;
					JSONArray dataList = messageObject.getJSONArray("data");
					JSONObject extData1 = messageObject.getJSONObject("extData1");
					mPage = extData1.getInt("nextPageNum");

					int dataSize = dataList.length();

					if(dataSize == 0)
					{
						alert("쪽지가 없습니다");
					}

					for(int i = 0 ; i < dataSize ; i++)
					{
						JSONObject data = (JSONObject) dataList.get(i);
						StarplMessage message = new StarplMessage(data);
						mMessageHistoryList.add(message);
					}

					if(mPage > 1)
					{
						toggleLockListView();
					}
					else
					{
						removeFooterView();
					}

					notifyDataSetChanged();
				}
				catch(JSONException e)
				{
					e.printStackTrace();
				}
			}
		};

		StarplCommand.getMessageWithSpecificUser(getMessageHistory, mUserInfo.getUserId(), mSendUserIdx, mPage);
	}

	/**
	 * @return
	 */
	private View addFooter()
	{
		View convertView = inflate(R.layout.message_history_footer);
		//TextView tvMessage = (TextView)convertView.findViewById(R.id.message_history_footer_tv_message);
		return convertView;
	}
	
	/* (non-Javadoc)
	 * @see com.starpl.platform.component.BaseListHandler#onInit()
	 */
	@Override
	public void onInit()
	{
		showFooterView(addFooter());
		showFooterView();
		showHeaderView();
		setAdapter();
		loadContent();
	}

	/**
	 * 차단해제 버튼 클릭시, 해당 유저에 대한 쪽지를 차단 해제한다.
	 */
	private void unblockMessage()
	{
		final HttpHandler unblockHandler = new HttpHandler(mParentActivity)
		{

			@Override
			public void didSucceed(Object result)
			{
				alert("앞으로 " + mSendUserNickName + "님의 쪽지를 받습니다.");
				mIbMessageBlock.setVisibility(ImageButton.VISIBLE);
				mIbMessageUnblock.setVisibility(ImageButton.INVISIBLE);
			}
			
		};
		
		DialogInterface.OnClickListener blockListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				StarplCommand.updateRejectedUserStatus(unblockHandler, mSendUserIdx, false);
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = mSendUserNickName + "님의<br>" +
				"쪽지 차단을 해제 하시겠습니까?";
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("차단해제", blockListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/**
	 * 쪽지차단 버튼 클릭시, 해당 유저에 대한 쪽지를 차단한다.
	 */
	private void blockMessage()
	{
		final HttpHandler blockHandler = new HttpHandler(mParentActivity)
		{

			@Override
			public void didSucceed(Object result)
			{
				alert("앞으로 " + mSendUserNickName + "님의 쪽지를 받지 않습니다.");
				mIbMessageBlock.setVisibility(ImageButton.INVISIBLE);
				mIbMessageUnblock.setVisibility(ImageButton.VISIBLE);
			}
			
		};
		
		DialogInterface.OnClickListener blockListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				StarplCommand.updateRejectedUserStatus(blockHandler, mSendUserIdx, true);
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = mSendUserNickName + "님의<br>" +
				"쪽지를 차단하겠습니까?";
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("차단", blockListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/**
	 * 모두삭제 버튼 클릭시 모든 쪽지를 삭제한다.
	 */
	private void deleteAllMessage()
	{
		final HttpHandler deleteAllHandler = new HttpHandler(mParentActivity)
		{

			@Override
			public void didSucceed(Object result)
			{
				refresh();
			}
			
		};
		
		DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				StarplCommand.deleteAllMessage(deleteAllHandler, mUserInfo.getUserId(), mSendUserIdx);
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = mSendUserNickName + "님과<br>" +
				"주고받은 모든 쪽지를<br>" +
				"모두 삭제하시겠습니까?";
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("삭제", deleteListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/**
	 * 내가 보낸 쪽지를 삭제한다.
	 * 
	 * @param msgIdx 삭제할 쪽지의 Idx
	 */
	private void deleteSendMessage(final int msgIdx)
	{
		final HttpHandler deleteSendMessageHandler = new HttpHandler(mParentActivity)
		{

			@Override
			public void didSucceed(Object result)
			{
				refresh();
			}
			
		};
		
		DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				StarplCommand.deleteSendedMessage(deleteSendMessageHandler, mUserInfo.getUserId(), msgIdx);
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = "정말 삭제하시겠습니까>";
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("삭제", deleteListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/**
	 * 받은 쪽지를 삭제한다.
	 * 
	 * @param msgIdx 삭제할 쪽지의 Idx
	 */
	private void deleteReceiveMessage(final int msgIdx)
	{
		final HttpHandler deleteReceiveMessageHandler = new HttpHandler(mParentActivity)
		{

			@Override
			public void didSucceed(Object result)
			{
				refresh();
			}
			
		};
		
		DialogInterface.OnClickListener deleteListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				StarplCommand.deleteReceivedMessage(deleteReceiveMessageHandler, mUserInfo.getUserId(), msgIdx);
				dialog.dismiss();
			}
		};
		
		DialogInterface.OnClickListener cancelListener = new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		};

		String text = "정말 삭제하시겠습니까?";
		
		new AlertDialog.Builder(mParentActivity)
			.setTitle(BaseApplication.getConfigPersistent("appsName"))
			.setMessage(Html.fromHtml(text))
			.setPositiveButton("삭제", deleteListener)
			.setNegativeButton("취소", cancelListener)
			.show();
	}
	
	/* (non-Javadoc)
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */
	@Override
	public void onClick(View v)
	{
		int position;
		StarplMessage message;
		Bundle extras;
		
		switch(v.getId())
		{
		
		// to.닉네임 클릭 -> 유저 프로필로 이동
		case R.id.message_history_header_tv_nickname:
		// 상대 유저 프로필 이미지 클릭 -> 유저 프로필로 이동
		case R.id.message_history_row_sender_iv_profile:
			extras = new Bundle();
			extras.putString("userId", mSendUserId);
			extras.putString("nickName", mSendUserNickName);
			getNewActivity().setTargetActivity(ProfileActivity.class).setBundle(extras).show();
			break;
		
		// 쪽지 보내기 버튼 클릭
		case R.id.message_history_header_ib_send:
			if(mEtInputComment.getText().length()<=0)
			{
				alert("쪽지 내용을 입력하세요");
			}
			else
			{
				HttpHandler sendMessage = new HttpHandler(mParentActivity, "쪽지 보내는 중")
				{
					@Override
					public void didSucceed(Object result)
					{
						toggleLockListView();
						mPage = 1;
						mEtInputComment.setText("");
						refresh();
					}
				};
				StarplCommand.sendMessage(sendMessage, mUserInfo.getUserId(), mSendUserIdx, mEtInputComment.getText().toString());
			}
			break;
		
		// (쪽지) 전체 삭제 클릭
		case R.id.message_history_header_ib_delete_all:
			deleteAllMessage();
			break;
			
		// 쪽지 차단 클릭
		case R.id.message_history_header_ib_message_block:
			blockMessage();
			break;
			
		// 차단해제 클릭
		case R.id.message_history_header_ib_message_unblock:
			unblockMessage();
			break;
			
		// 내(보낸) 쪽지 삭제
		case R.id.message_history_row_receiver_ib_delete:
			position = (Integer)v.getTag();
			message = mMessageHistoryList.get(position);
			deleteSendMessage(message.getMsgIdx());
			break;

		// 받은 쪽지 삭제
		case R.id.message_history_row_sender_ib_delete:
			position = (Integer)v.getTag();
			message = mMessageHistoryList.get(position);
			deleteReceiveMessage(message.getMsgIdx());
			break;
		}
	}

	/**
	 * row 재활용에 사용되는 뷰홀더 클래스
	 * 
	 * @author 우연화
	 * @since 2011.02.22
	 */
	public class MessageHistoryViewHolder
	{
		public LinearLayout llSenderRow;
		public ImageView ivSenderProfile;
		public TextView tvSenderComment;
		public TextView tvSenderDate;
		public ImageButton ibSenderDelete;
		
		public LinearLayout llReceiverRow;
		public ImageView ivReceiverProfile;
		public TextView tvReceiverComment;
		public TextView tvReceiverDate;
		public ImageButton ibReceiverDelete;
	}
}
